#include<iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>

class udpserver
{
private:
    int _sockfd;
    std::string _ip;
    int _port;
public:
    udpserver(std::string ip, int port)
        :_sockfd(-1)
        ,_ip(ip)
        ,_port(port)
    {}


    bool InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        { 
            std::cerr << "create socket fail!" << std::endl;
            return false;
        }

        std::cout << "create socket success!" << std::endl;
        std::cout << _sockfd << std::endl;

       struct sockaddr_in local;
		memset(&local, '\0', sizeof(local));
		local.sin_family = AF_INET;
		local.sin_port = htons(_port);
        //让外网获取, 需要多传INADDR_ANY才可以;
		local.sin_addr.s_addr = INADDR_ANY;                                                                                                                                                                                                                                                                                                                                                                                                        

		//绑定
		if (bind(_sockfd, (struct sockaddr*)&local, sizeof(sockaddr)) < 0){ //绑定失败
			std::cerr << "bind error" << std::endl;
			return false;
		}
        std::cout << "create bind success!" << std::endl;

        return true;
    }

    void start()
    {
   #define SIZE 128
		char buffer[SIZE];
		for (;;)
        {
			struct sockaddr_in peer;
			socklen_t len = sizeof(peer);
			ssize_t size = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
			if (size > 0)
            {
				buffer[size] = '\0';
				int port = ntohs(peer.sin_port);
				std::string ip = inet_ntoa(peer.sin_addr);
				std::cout << ip << ":" << port << "# " << buffer << std::endl;
			}
			else
            {
				std::cerr << "recvfrom error" << std::endl;
			}

            std::string echo_msg = "server get->";
            echo_msg += buffer;
            sendto(_sockfd, echo_msg.c_str(), echo_msg.size()-1, 0, (struct sockaddr*)&peer, len);
		}
    }

    ~udpserver()
    {
        if(_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
};


int main(int argc, char* argv[])
{
    //两个参数; ip和port;
    if(argc != 2)
    {
        std::cerr << "Useage: " << argv[0] << "port" << std::endl;
        return 0;
    }

    //本地回环ip地址;
    std::string ip = "127.0.0.1";
    int port = atoi(argv[1]);

    udpserver* sur = new udpserver(ip, port);
    sur->InitServer();
    sur->start();
    return 0;
}